<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <canvas id="ctx" width="1000" height="1000" style="background-color: #eee;"></canvas>
</body>
</html>

<script>

const canvas = document.querySelector('#ctx')
const ctx = canvas.getContext('2d')
let isMouseDown = false

function clearRect(){
  ctx.clearRect(0, 0, canvas.width, canvas.height)
}

function DrawRect(context, x, y, width, height){
  this.context = context
  this.x = x || 0
  this.y = y || 0
  this.width = width || 0
  this.height = height || 0
  this.offset = 0
  this.timer = 0
}
DrawRect.prototype.drawRect = function(){
  clearRect()
}

DrawRect.prototype.drawDash = function(){
  const draw = ()=>{
    clearRect()
    this.context.setLineDash([4, 4]);
    this.context.lineWidth = 1
    this.context.lineDashOffset = this.offset
    this.context.strokeRect(this.x, this.y, this.width, this.height);
    this.context.fillStyle = 'rgba(0,0,0,.1)'
    this.context.fillRect(this.x, this.y, this.width, this.height)
  }
  draw()
  clearInterval(this.timer)
  this.timer = setInterval(()=>{
    this.offset++;
    if (this.offset > 16) {
      this.offset = 0;
    }
    draw()
  },33)
}


let rect = new DrawRect(ctx)
canvas.addEventListener('mousedown', function(event){
  isMouseDown = true
  rect.width = 0 
  rect.height = 0
  rect.x = event.offsetX
  rect.y = event.offsetY
})

canvas.addEventListener('mousemove', function(event){
  if(!isMouseDown)return
  rect.width = event.offsetX - rect.x
  rect.height = event.offsetY - rect.y
  rect.drawDash()
})

canvas.addEventListener('mouseup', function(event){
  isMouseDown = false
  clearInterval(this.timer)
})




</script>